# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/10/21
# @File   : TX13_AvgTaxGVatRatio.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:近1年月均增值税
code:TX13_AvgTaxGVatRatio
tableName:
columnName:
groups:税务模块
dependencies:TX_CQ_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


# -*- coding: utf-8 -*-
# @Author : breeze
# @Date   : 2021/02/23
# @File   : TX12_VatRatio.py
# @E-mail : wangbaoshan@bbdservice.com

'''eof
name:近1年月均增值税
code:TX13_AvgTaxGVatRatio
tableName:
columnName:
groups:税务模块
dependencies:TX_CQ_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import re
import sys
import datetime
import pandas as pd
import math
import json
from dateutil import rrule
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding('utf-8')


def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = TX_CQ_DSJ["data"].get(table_Name)
        return data if isinstance(data, list) and len(data) > 0 else [{}]

    except:
        return [{}]


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


def dataPre(dataList=None, key=None):
    """
    对list里面的列表去重月份不标准的
    :param dataList:
    :param key:
    :return:
    """
    dataListTemp = dataList
    data = []
    for i in range(len(dataListTemp)):
        temp = dataListTemp[i].get(key)
        try:
            temp = int(temp)
        except:
            temp = None
            pass

        if temp:
            data.append(dataListTemp[i])
        else:
            pass

    if len(data) == 0:
        data = [{}]
    else:
        pass

    return data


def vatDataMerge(syptZzsxgm, syptZzsybnsr, syptSwdjxx, putBackYear=2, CcrDate=None):
    """
    增值税纳税数据拆分为近两年的月度数据

    :param syptZzsxgm:小规模增值税纳税表[{}]
    :param syptZzsybnsr:一般纳税人增值税表[{}]
    :param putBackYear:回推时间，默认为2年
    :return: VatData为Series
    """
    syptZzsybnsr = dataPre(syptZzsybnsr, key='YF')
    syptZzsxgm = dataPre(syptZzsxgm, key='YF')
    NSRZG_DM = syptSwdjxx[0].get('NSRZG_DM')

    # 生成时间轴
    dateIndexList = []
    if CcrDate is None:
        CcrYearMonth = datetime.datetime.now().strftime('%Y-%m-%d')[:7]
        CcrDate = CcrYearMonth + '-01'
        StartDateTmp = str(datetime.datetime.now().year - putBackYear) + CcrDate[4:]
        StartDate = StartDateTmp[:7] + '-01'
    else:
        CcrYear = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().year
        CcrDate = convertDataType(CcrDate, 'date_time')[:7] + '-01'
        StartDate = str(CcrYear - putBackYear) + convertDataType(CcrDate, 'date_time')[4:]

    dateSet = pd.date_range(StartDate, CcrDate, freq='M')
    for i in dateSet:
        year = i.date().year
        month = i.date().month
        dateIndexList.append(str(year) + str(month))

    VatData = pd.Series(None, index=dateIndexList)

    if syptZzsxgm == [{}] and syptZzsybnsr == [{}]:
        return VatData
    else:
        if NSRZG_DM == u'204' or NSRZG_DM == u'205':
            NSRZG = 'xgn'
        else:
            NSRZG = 'yb'
        if NSRZG == 'yb':
            parse_data(syptZzsybnsr, VatData, "YNSEHJ")
            parse_data(syptZzsxgm, VatData, "YNSEHJDBNBQ")
            if math.isnan(VatData.iloc[-1]):
                VatData.drop(dateIndexList[-1], inplace=True)
        else:
            parse_data(syptZzsxgm, VatData, "YNSEHJDBNBQ")
            parse_data(syptZzsybnsr, VatData, "YNSEHJ")
            if math.isnan(VatData.iloc[-1]):
                VatData.drop(dateIndexList[-1], inplace=True)
            if math.isnan(VatData.iloc[-1]):
                VatData.drop(dateIndexList[-2], inplace=True)
            if math.isnan(VatData.iloc[-1]):
                VatData.drop(dateIndexList[-3], inplace=True)

    return VatData


def parse_data(sypt_zzs, zzs_list, column):
    if (sypt_zzs) == [{}]:
        return zzs_list
    for i in range(len(sypt_zzs)):
        sypt_zzs = sorted(sypt_zzs, key=lambda x: int(x['YF']))
        try:
            ND_q = int(sypt_zzs[i]["skssqq"][0:4])
            ND_z = int(sypt_zzs[i]["skssqz"][0:4])
            YF_q = int(sypt_zzs[i]["skssqq"][5:7])
            YF_z = int(sypt_zzs[i]["skssqz"][5:7])

            time_q = datetime.datetime(ND_q, YF_q, 1)
            time_z = datetime.datetime(ND_z, YF_z, 1)
            time_gap = rrule.rrule(rrule.MONTHLY, dtstart=time_q, until=time_z).count()
            for j in range(time_gap):
                change_time = time_z - relativedelta(months=+j)
                ND = change_time.year
                YF = change_time.month
                if ND and YF:
                    NDYF = str(ND) + str(YF)
                    if NDYF in zzs_list.index:
                        tax_amount = convertDataType(sypt_zzs[i].get(column), 'float')
                        if tax_amount:
                            if math.isnan(zzs_list.loc[NDYF]):
                                zzs_list.loc[NDYF] = tax_amount / time_gap
        except:
            pass


def TX12_VatRatio(spDate=None):
    syptZzsxgm = formatData('syptZzsxgm')
    syptZzsybnsr = formatData('syptZzsybnsr')
    syptSwdjxx = formatData('syptSwdjxx')

    # 增值税数据合并
    if syptZzsybnsr == [{}] and syptZzsxgm == [{}]:
        return u'缺失值'
    else:
        vatDataSeries = vatDataMerge(syptZzsxgm=syptZzsxgm, syptZzsybnsr=syptZzsybnsr, syptSwdjxx=syptSwdjxx,
                                     putBackYear=2, CcrDate=spDate)
        vatDataSeries = vatDataSeries.fillna(value=0)

        latest3monthsVat = sum(vatDataSeries[-3:])
        latest1yearVat = sum(vatDataSeries[-12:])
        try:
            return  round(float(latest1yearVat)/12,4)
        except:
            return u'缺失值'


if __name__ == "__main__":
    file_obj = open(r'../data/TX/TX12_VatRatio/TX_CQ_DSJ.json', 'r')
    content = file_obj.read()
    TX_CQ_DSJ = json.loads(content, strict=False)
    aa = TX12_VatRatio()
    print aa

result = TX12_VatRatio()
